/**
Auhtor      : Andrey Volosevich
Company     : Fujitsu America
Created Date: 05 Oct-2009
Modified    : 
Description : Test class for preventContactDeleteTrigger 
NOTE: The functionality of the trigger assumes that non-Admin user prfiles have 'ModifyAll' permission on COntact object. 
If this profile setting changes for any user profile (except thoselisted in the Label.IM_Admin_Profiles then the unit test 
may not function properly and will need to change along with the trigger to match new configuration.)
*/

@isTest
private class preventContactDeleteTriggerTest {

	static User nonAdminUser;
	static User adminUser;
	static Contact[] conForDelete = new List<Contact>();
	
	private static void setupTestDataHelper(){
		for(Integer i=0; i<200; i++){
		 	Contact testCon = new Contact(Lastname = 'Test Contact'+String.valueOf(i), Email = 'test@test.test');
		 	conForDelete.add(testCon);
		 }  
		 
		insert conForDelete;
		 		 
		 
		Set<String> adminProfiles = new Set<String>();
		adminProfiles.addAll(Label.IM_Admin_Profiles.split(';'));
		System.debug('Admin (Allowed) Profiles: ' + adminProfiles);
		 
		List<User> nonAdminUsers = new List<User>([Select Id, Name, ProfileId from User where IsActive = true and Profile.Name not in: adminProfiles ]);
		List<User> adminUsers = new List<User>([Select Id, Name, ProfileId from User where IsActive = true and Profile.Name in: adminProfiles ]);
		
		if(nonAdminUsers.size()>0)
			nonAdminUser = nonAdminUsers[0];
		
		if (adminUsers.size()>0)
			adminUser = adminUsers[0];
		
		
	
	}

    static testMethod void testPreventContactDeleteAsNonAdmin() {
        
        setupTestDataHelper();
		
		Test.startTest();
		//Deleting Contact for non-Admin Profiles
		if(nonAdminUser!=null){
			System.runAs(nonAdminUser){
		 		try{
		 			delete conForDelete;
		 		}
		 		catch(Exception ex){
		 			System.assert(
		 				(
		 				ex.getMessage().contains('Insufficient privileges to delete Contact.')
		 				||
		 				ex.getMessage().contains('INSUFFICIENT_ACCESS_OR_READONLY')
		 				),
		 				'Exception Message: ' + ex.getMessage());
		 		}
		 	}
		 }
		 Test.stopTest();
    }
    
    
    static testMethod void testPreventContactDeleteAsAdmin() {
        
        setupTestDataHelper();
		
		Test.startTest();
		//Deleting Contact for Admin Profiles
		if(adminUser!=null){
		 	System.runAs(adminUser){
		 		delete conForDelete;
			}
		}
		Test.stopTest();
    }
    
}